<template>
  <div class="search-box">
    <a-modal v-model:visible="open" width="500px" :title="`${!!searchForm.id ? '编辑' : '新建'}标签`" :confirmLoading="loading" @cancel="hideModal" @ok="handleOk">
      <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="标签名称" v-bind="validateInfos.tagName">
          <a-input v-model:value="searchForm.tagName" placeholder="请输入标签名称" />
        </a-form-item>
        <a-form-item label="状态">
          <a-switch v-model:checked="status" checked-children="启用" un-checked-children="停用" />
        </a-form-item>
        <a-form-item label="标签类型">
          <a-radio-group v-model:value="searchForm.tagType" name="radioGroup">
            <a-radio v-for="item in TAG_TYPE_OPTIONS" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { Form } from 'ant-design-vue'
  import message from 'ant-design-vue/es/message'
  import { onMounted, reactive, ref, toRaw } from 'vue'

  import { requestSaveTag } from '/@/api/exchange/tagManage'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  import { TAG_TYPE_OPTIONS } from '../constants'

  const emit = defineEmits<(e: 'reload', type?: number) => void>()
  const open = ref<boolean>(false)
  const loading = ref<boolean>(false)
  const status = ref<boolean>(true)

  const labelCol = { style: { width: '150px' } }
  const wrapperCol = { span: 14 }
  const searchForm = reactive<TagManageTypes.IAddTag>({
    id: undefined,
    tagName: '',
    tagType: 0,
    isUsed: 1,
  })

  const rulesRef = reactive({
    tagName: [
      {
        required: true,
        message: '请输入标签名称',
      },
      { pattern: /^[^\s]{1}|.*[^\s].*$/, message: '请输入1-32位的有效标签名称' },
      { pattern: /^.{1,32}$/, message: '请输入1-32位的标签名称' },
    ],
  })

  const { resetFields, validate, validateInfos } = Form.useForm(searchForm, rulesRef, {})

  // 打开弹窗
  const showModal = (info?: TagManageTypes.IResponse) => {
    if (info) {
      status.value = info.isUsed === 1
      Object.assign(searchForm, info)
    }
    open.value = true
  }
  // 关闭弹窗
  const hideModal = () => {
    // 清空和恢复默认
    resetFields()
    open.value = false
    loading.value = false
  }

  // 更新标签
  const updateTag = async () => {
    return await requestSaveTag({
      ...toRaw(searchForm),
      isUsed: status.value ? 1 : 0,
    })
  }

  // 提交
  const handleOk = () => {
    validate().then(async () => {
      loading.value = true
      const res = await updateTag()
      if (res?.responseCode === HttpCodeEnum.SUCCESS) {
        message.success('操作成功')
        hideModal()
        emit('reload')
      }
      loading.value = false
    })
  }

  onMounted(() => {})

  defineExpose({
    showModal,
  })
</script>
<style lang="less" scoped>
  .add-entity {
    position: absolute;
    right: -100px;
  }
</style>
